/**
 * @created by huajb on 2020-10-29 15:27:40
 * @updated by
 * @description 首页
 */
define([
	'./custom/widgets/js/yufpOrgTree.js',
	'./custom/widgets/js/yufpExtTree.js',
	'./libs/moment/moment.js',
	'./custom/plugins/YufpMgrSelector.js'
], function(require, exports) {
	exports.ready = function(hashCode, data, cite) {
		yufp.lookup.reg('MARKET_TASK_STAT,TARGET_TYPE,YES_NO');
		var level1RoleIds = "R0006,R0007,R0008"; //总行
		var level2RoleIds = "R0003,R0004,R0005"; //支行
		var level3RoleIds = "R0001,R0002,R0009"; //客户经理
		var roleCode = '';
		var roleLevel = '';
		var roleName = '';
		for (var i = 0; i < yufp.session.roles.length; i++) {
			if (yufp.session.roles[i].checked != null) {
				roleCode = yufp.session.roles[i].code;
				if (level1RoleIds.indexOf(roleCode) != -1) {
					roleLevel = '1';
				} else if (level2RoleIds.indexOf(roleCode) != -1) {
					roleLevel = '2';
				} else if (level3RoleIds.indexOf(roleCode) != -1) {
					roleLevel = '3';
				}
				roleName = yufp.session.roles[i].name;
			}
		}
		var orgId = yufp.session.org.id;
		var userId = yufp.session.userId;
		yufp.custom.vue({
			el: cite.el,
			data: function() {
				return {
					marketTaskDownTab: !yufp.session.checkCtrl('marketTaskDownTab'), //营销任务下达tab页
					marketTaskAnalysis: !yufp.session.checkCtrl('marketTaskAnalysis'), //营销达成分析tab
					myMarketTaskTab: !yufp.session.checkCtrl('myMarketTaskTab'), //我的营销任务tab页
					taskAddButton: !yufp.session.checkCtrl('markeTaskAdd'), // 营销任务新增
					taskEditButton: !yufp.session.checkCtrl('markeTaskEdit'), // 营销任务修改
					taskDetailButton: !yufp.session.checkCtrl('markeTaskDetail'), // 营销任务详情
					taskDeleteButton: !yufp.session.checkCtrl('marketDelete'), //营销任务删除
					taskDownButton: !yufp.session.checkCtrl('marketDown'), // 营销任务下达
					marketTask: {},
					mydetailDialogVisible: false,
					mydetailData: {},
					execOption: [],
					activeFlag: '',
					addDialogVisible: false,
					transmitDialogVisible: false,
					targetDialogVisible: false,
					targetVlueDialogVisible: false,
					marketTaskParams: {
						condition: JSON.stringify({
							roleCode: roleCode,
							roleLevel: roleLevel,
							orgId: orgId,
							userId: userId
						})
					},
					myMarketTaskParams: {
						condition: JSON.stringify({
							roleCode: roleCode,
							roleLevel: roleLevel,
							orgId: orgId,
							userId: userId
						})
					},
					params: {
						needCheckbox: true,
						checkStrictly: true
					},
					addTaskData: {},
					transmitTaskData: {},
					indexValue: '',
					group: {},
					title: '',
					indexData: [],
					childindexValue: [],
					detailData: {},
					targetData: {},
					targetValueData: {},
					performType: false,
					detailDialogVisible: false,
					indexCaliberDisabled: false,
					giveDialogVisible: false,
					addFormDisabled: false,
					giveFormdata: {},
					indexTitle: '',
					detailIndexValue: [],
					detailChildindexValue: [],
					showIndexCaliber: false,
					rule: {
						checkNum: [{
								validator: yufp.validator.gZero,
								message: '请输入数字'
							},
							{
								required: true,
								message: '请填写指标任务值',
								trigger: 'blur'
							}
						],
						remark: [{
								max: 200,
								message: '最大长度不超过200个字符',
								trigger: 'blur'
							},
							{
								required: false,
								message: '字段不能为空',
								trigger: 'blur'
							}
						]
					},
					indexRule: [{
						required: true,
						validator: yufp.validator.digit,
						message: '输入数字',
						trigger: 'blur'
					}],
					marketTaskUrl: '/api/marketTaskManager/taskQuery',
					mymarketTaskUrl: '/api/marketTaskManager/taskQuery',
					taskGroupsUrl: '/api/marketTaskManager/getTaskGroups',
					taskGroupsParam: {
						condition: JSON.stringify({
							orgId: orgId,
							roleLevel: roleLevel,
							userId: userId
						})
					},
					checked: false,
					selectedArray: [],
					levelGrid: [],
					// taskGridUrl: '/api/marketTaskManager/getLevelGrid',
					// taskGridParam: {
					// 	condition: JSON.stringify({
					// 		roleCode: roleCode,
					// 		roleLevel: roleLevel,
					// 		orgId: orgId,
					// 		userId: userId,
					// 	})
					// },
					targetTaskUrl: '/api/marketTaskManager/targetTask',
					targetTaskParams: {},
					targetValueTaskUrl: '/api/marketTaskManager/targetTask',
					// targetValueTaskParams:{},
					// targetTaskParams: {
					// 	condition: JSON.stringify({
					// 		userId: yufp.session.userId,
					// 		userName: yufp.session.userName,
					// 		// taskNo: row.taskNo,
					// 		// gridId: row.gridId,
					// 		roleLevel: roleLevel
					// 	})
					// },
					// AnalyMarketTaskUrl: '/api/MarkertManager/analyTask',
					//   AnalyMarketTaskParams: {condition: JSON.stringify({
					//                                         roleCode: roleCode,
					//                                         roleLevel: roleLevel,
					//                                         orgId: orgId,
					//                                         userId: userId
					//                                       })}
				};
			},
			mounted: function() {
				if (data == '1') {
					this.activeFlag = 'third';
				} else {
					//this.activeFlag = 'first';
					this.activeFlag = this.marketTaskDownTab ? 'first' : (this.myMarketTaskTab ? 'second' : (this.marketTaskAnalysis ?
						'third' : ''));
				}
				this.getLevelGrid();
			},
			methods: {
				//时间格式化
				dateFormat: function (row, column) {
				    var date = row[column.property];
				    if (date == undefined) {
				        return "";
				    }
				    return moment(date).format("YYYY-MM-DD");
				},
				dateTimeFormat: function (row, column) {
				    var date = row[column.property];
				    if (date == undefined) {
				        return "";
				    }
				    return moment(date).format("YYYY-MM-DD HH:mm:ss");
				},
				dbSelected: function(row) {
					console.log(row);
					var _this = this;
					_this.detailDialogVisible = true;
					_this.$nextTick(function() {
						_this.$refs.refForm.resetFields();
						yufp.extend(_this.detailData, row, true);
					});
					yufp.service.request({
						method: 'get',
						url: '/api/MarkertManager/getDetailValue',
						data: {
							condition: JSON.stringify({
								upTaskNum: row.marketTaskNum
							})
						},
						callback: function(code, message, response) {
							if (code == 0) {
								_this.detailIndexValue = response.data.upIndexList;
								_this.detailChildindexValue = response.data.childIndexList;
							}
						}
					});
				},
				taskdetail: function() {
					var _this = this;
					if (_this.$refs.marketTaskTable.selections.length != 1) {
						_this.$message({
							message: '请先选择一条记录',
							type: 'warning'
						});
						return;
					}
					_this.detailDialogVisible = true;
					_this.$nextTick(function() {
						_this.$refs.refFormDetail.resetFields();
						yufp.extend(_this.detailData, _this.$refs.marketTaskTable.selections[0], true);
					});
				},
				mytaskdetail: function() {
					var _this = this;
					if (_this.$refs.mymarketTaskTable.selections.length != 1) {
						_this.$message({
							message: '请先选择一条记录',
							type: 'warning'
						});
						return;
					}
					_this.mydetailDialogVisible = true;
					_this.$nextTick(function() {
						_this.$refs.myRefFormDetail.resetFields();
						yufp.extend(_this.mydetailData, _this.$refs.mymarketTaskTable.selections[0], true);
					});
				},

				getLevelGrid: function() {
					var _this = this;
					yufp.service.request({
						method: 'get',
						url: '/api/marketTaskManager/getLevelGrid',
						data: {
							condition: JSON.stringify({
								roleCode: roleCode,
								roleLevel: roleLevel,
								orgId: orgId,
								userId: userId
							})
						},
						callback: function(code, message, response) {
							if (code == 0) {
								_this.levelGrid = response.data;
							}
						}
					});
				},
				selectAll: function() {
					this.selectedArray = []
					if (this.checked) {
						this.levelGrid.map((item) => {
							this.selectedArray.push(item.key)
						})
					} else {
						this.selectedArray = []
					}
				},
				changeSelect: function(val) {
					if (val.length === this.levelGrid.length) {
						this.checked = true
					} else {
						this.checked = false
					}
				},

				// change: function(key) {
				// 	this.addTaskData.execTopyNum = '';
				// 	this.addTaskData.execTopyName = '';
				// 	if (key == '3') {
				// 		this.performType = true;
				// 	} else {
				// 		this.performType = false;
				// 	}
				// },
				taskadd: function() {
					this.funcSwitchStatus('新增营销任务', true);
					this.$nextTick(function() {
						this.$refs.refForm.resetFields();
					});
				},
				//操作状态选择
				funcSwitchStatus: function(viewType, editable) {
					this.title = viewType;
					this.addDialogVisible = true;
					this.addFormDisabled = !editable;
				},
				taskgive: function() {
					var _this = this;
					if (_this.$refs.marketTaskTable.selections.length != 1) {
						_this.$message({
							message: '请先选择一条记录',
							type: 'warning'
						});
						return;
					}
					if (_this.$refs.marketTaskTable.selections[0].gridStat == '02') {
						_this.$message({
							message: '只能下发暂存和派发中的任务',
							type: 'warning'
						});
						return;
					}
					this.transmitDialogVisible = true;
					this.$nextTick(function() {
						this.$refs.refFormTransmit.resetFields();
					});
				},
				setOrgName: function(data) {
					console.log(data);
					var result = false;
					var orgId = '';
					var orgName = '';
					for (var i = 0; i < data.length; i++) {
						console.log(data[i]);
						console.log(parseInt(this.addTaskData.execTopyType) + 2);
						if (data[i].orgLevel != parseInt(this.addTaskData.execTopyType) + 2) {
							this.$message({
								message: '执行对象与执行对象类型不对应，请重新选择',
								type: 'warning'
							});
							result = false;
							break;
						}
						if (i == 0) {
							orgId += data[i].orgId;
							orgName += data[i].orgName;
						} else {
							orgId += ',' + data[i].orgId;
							orgName += ',' + data[i].orgName;
						}
						result = true;
					}
					console.log(result);
					this.addTaskData.execTopyNum = result ? orgId : '';
					console.log(this.$refs);
					this.addTaskData.execTopyName = result ? orgName : '';
				},
				setExecName: function(data) {
					console.log(data);
					this.addTaskData.execTopyName = data;
				},
				taskedit: function() {
					var _this = this;
					if (_this.$refs.marketTaskTable.selections.length != 1) {
						_this.$message({
							message: '请先选择一条记录',
							type: 'warning'
						});
						return;
					}
					if (_this.$refs.marketTaskTable.selections[0].gridStat != '01') {
						_this.$message({
							message: '只能修改暂存的任务',
							type: 'warning'
						});
						return;
					}
					_this.funcSwitchStatus('修改营销任务', true);
					_this.$nextTick(function() {
						var aa = _this.addTaskData;
						yufp.extend(_this.addTaskData, _this.$refs.marketTaskTable.selections[0], true);
					});
					// yufp.service.request({
					// 	method: 'get',
					// 	url: '/api/MarkertManager/getTaskValueData',
					// 	data: {
					// 		condition: JSON.stringify({
					// 			childTaskNum: '',
					// 			taskNum: _this.$refs.marketTaskTable.selections[0].marketTaskNum
					// 		})
					// 	},
					// 	callback: function(code, message, response) {
					// 		if (code == 0) {
					// 			_this.indexValue = response.data.valueList;
					// 			_this.addTaskData.indexVa = response.data.indexVa;
					// 			_this.addTaskData.execTopyNum = response.data.execTopyNum;
					// 		}
					// 	}
					// });
				},
				//删除
				taskdelete: function() {
					var _this = this;
					var selections = _this.$refs.marketTaskTable.selections;
					if (selections.length < 1) {
						_this.$message({
							message: '请至少选择一条记录',
							type: 'warning'
						});
						return;
					}
					var taskNums = '';
					for (var i = 0; i < selections.length; i++) {
						if (_this.$refs.marketTaskTable.selections[0].gridStat != '01') {
							// if (roleLevel != '1' && selections[i].createUser != yufp.session.userId) {
							_this.$message({
								// message: '删除失败，只能删除自己创建的营销任务',
								message: '删除失败，只能删除暂存的任务',
								type: 'warning'
							});
							return;
						}
						taskNums = taskNums + ',' + selections[i].taskNo;
					}
					console.log(taskNums);
					_this.$confirm('确认删除该营销任务?', '提示', {
						callback: function(action) {
							if (action === 'confirm') {
								yufp.service.request({
									method: 'GET',
									url: '/api/marketTaskManager/deleteTask/' + taskNums,
									callback: function(code, message, response) {
										if (code == 0 && response.data > 0) {
											_this.$message({
												message: '删除成功',
												type: 'success'
											});
											_this.$refs.marketTaskTable.remoteData();
										} else {
											_this.$message({
												message: '删除失败',
												type: 'warning'
											});
										}
									}
								});
							}
						}
					});
				},
				//下达
				transmitFn: function() {
					var _this = this;
					var model = {};
					_this.transmitTaskData.gridIds=_this.selectedArray;
					yufp.extend(_this.transmitTaskData, _this.$refs.marketTaskTable.selections[0], true);
					// yufp.extend(_this.selectedArray, _this.$refs.marketTaskTable.selections[0], true);
					model = _this.transmitTaskData;
					model.userId = yufp.session.userId;
					model.userName = yufp.session.userName;
					model.roleLevel = roleLevel;
					yufp.service.request({
						method: 'POST',
						url: '/api/marketTaskManager/giveTask',
						data: model,
						callback: function(code, message, response) {
							if (code == 0 && response.data > 0) {
								_this.$message({
									message: '下达成功',
									type: 'success'
								});
								_this.transmitDialogVisible = false;
								_this.$refs.marketTaskTable.remoteData();
								_this.$refs.marketTaskTable.resetFields();
							}
						}
					});
				},
				cancelFn: function() {
					this.addDialogVisible = false;
					this.transmitDialogVisible = false;
				},
				saveAddFn: function() {
					var _this = this;
					// var parseTime = yufp.util.dateFormat;
					var model = {};
					var validate = false;
					_this.$refs.refForm.validate(function(valid) {
						validate = valid;
					});
					if (!validate) {
						_this.$message({
							message: '请检查输入项是否合法',
							type: 'warning'
						});
						return;
					}
					if (_this.addTaskData.endDt < _this.addTaskData.startDt) {
						_this.$message({
							message: '任务开始时间不能大于结束时间',
							type: 'warning'
						});
						return;
					}

					console.log(_this.addTaskData);
					yufp.clone(_this.addTaskData, model);
					model.indexName = _this.indexValue;
					// model.startDt = parseTime(_this.addTaskData.startDt, '{y}-{m}-{d}');
					// model.endDt = parseTime(_this.addTaskData.endDt, '{y}-{m}-{d}');
					model.userId = yufp.session.userId;
					model.orgId = yufp.session.org.id;
					model.orgName = yufp.session.org.name;
					model.userName = yufp.session.userName;
					if (_this.title == "新增营销任务") {
						yufp.service.request({
							method: 'POST',
							url: '/api/marketTaskManager/insertData',
							data: model,
							callback: function(code, message, response) {
								if (code == 0 && response.data > 0) {
									_this.$message({
										message: '新增成功',
										type: 'success'
									});
									_this.addDialogVisible = false;
									_this.$refs.marketTaskTable.remoteData();
								} else {
									_this.$message({
										message: '新增失败',
										type: 'warning'
									});
								}
							}
						});
					} else if (_this.title == "修改营销任务") {
						yufp.service.request({
							method: 'POST',
							url: '/api/marketTaskManager/editData',
							data: model,
							callback: function(code, message, response) {
								if (code == 0 && response.data > 0) {
									_this.$message({
										message: '修改成功',
										type: 'success'
									});
									_this.addDialogVisible = false;
									_this.$refs.marketTaskTable.remoteData();
								} else {
									_this.$message({
										message: '修改失败',
										type: 'error'
									});
								}
							}
						});
					}

				},
				selectIndexFn: function(val) {
					var value = yufp.lookup.convertKey('TARGET_TYPE', val);
					this.indexValue = value;
				},
				myMarketSearchFn: function() {
					var vm = this;
					window.console.info(vm.$refs.myMarketSearchForm.formdata);
					var param = {
						condition: JSON.stringify({
							marketTaskName: vm.$refs.myMarketSearchForm.formdata.marketTaskName,
							upMarketTaskName: vm.$refs.myMarketSearchForm.formdata.upMarketTaskName,
							marketTaskType: vm.$refs.myMarketSearchForm.formdata.marketTaskType,
							gridStat: vm.$refs.myMarketSearchForm.formdata.gridStat
						})
					};
					this.$refs.mymarketTaskTable.remoteData(param);
				},
				//指标完成情况
				handleClick: function(row) {
					var _this = this;
					if (row.gridStat == '01') {
						_this.$message({
							message: '当前任务未下发',
							type: 'warning'
						});
						return;
					}
					var index1 = "01,02,03,04,05,12,13,14";
					var index2 = "06,07,08,09,10,11,15,16";
					var indexNo = row.indexNo;
					var indexFalg;
					if (index1.indexOf(indexNo) != -1) {
						indexFalg = 1;
					} else if (index2.indexOf(indexNo) != -1) {
						indexFalg = 2;
					}
					var targetTaskParams = {
						condition: JSON.stringify({
							userId: yufp.session.userId,
							userName: yufp.session.userName,
							taskNo: row.taskNo,
							gridId: row.gridId,
							roleLevel: roleLevel,
							indexFalg: indexFalg

						})
					};
					_this.targetTaskParams = targetTaskParams;
					if (indexFalg == 1) {
						_this.targetDialogVisible = true;
						_this.targetVlueDialogVisible = false;
						_this.$nextTick(function() {
							_this.$refs.targetTable.resetFields();
						});
					} else if (indexFalg == 2) {
						_this.targetVlueDialogVisible = true;
						_this.targetDialogVisible = false;
						_this.$nextTick(function() {
							_this.$refs.targetValueTable.resetFields();
						});
					}

				}
			}
		});
	};

	/**
	 * 页面传递消息处理
	 * @param type 消息类型
	 * @param message 消息内容
	 */
	exports.onmessage = function(type, message) {};

	/**
	 * 页面销毁时触发destroy方法
	 * @param id 路由ID
	 * @param cite 页面站点信息
	 */
	exports.destroy = function(id, cite) {};
});
